/* eslint-disable react-refresh/only-export-components */
import { NavLink, useNavigate } from "react-router-dom";
import {
  CommentOutlined,
  TeamOutlined,
  SettingOutlined,
  MenuFoldOutlined,
  LogoutOutlined
} from "@ant-design/icons";
import { memo, useState } from "react";
import { message, Modal, Dropdown } from "antd";
import type { FC, Dispatch, SetStateAction } from "react";
import { useDispatch } from "react-redux";
import { setStoreItem } from "@/util/storage";
import mysocket from "@/api/socket/initSocket";
import history from "@/router/config";
interface LeftNavProps {
  setisshowNav: Dispatch<SetStateAction<boolean>>;
}
const LeftNav: FC<LeftNavProps> = function (props) {
  const dispatch = useDispatch();
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleLogout = () => {
    setIsModalOpen(true);
  };

  const confirmLogout = () => {
    // 关闭socket连接
    mysocket.socketDisconnect();
    
    // 删除本地存储
    setStoreItem("userinfo", "{}");
    setStoreItem("token", "");
    localStorage.removeItem("userinfo");
    sessionStorage.removeItem("token");
    
    // 清除Redux状态
    dispatch({ type: "user/setUser", payload: {id: null, userName: null} });
    
    // 显示消息
    message.success("已安全退出登录");
    
    // 关闭Modal
    setIsModalOpen(false);
    
    // 跳转到登录页
    setTimeout(() => {
      console.log("跳转到登录页");
      history.navigate("/login");
    }, 1000);
  };

  const settingItems = [
    {
      key: "logout",
      label: (
        <div className="flex items-center" onClick={handleLogout}>
          <LogoutOutlined className="mr-1" />
          <span>退出登录</span>
        </div>
      ),
    },
  ];

  return (
    <>
      <NavLink
        to={"message"}
        className={({ isActive }) => {
          return isActive ? "text-red-700" : "";
        }}
      >
        <CommentOutlined className="text-lg mt-4" />
      </NavLink>
      <NavLink
        to={"friends"}
        className={({ isActive }) => {
          return isActive ? "text-red-700" : "";
        }}
      >
        <TeamOutlined className="text-lg mt-4" />
      </NavLink>
      <MenuFoldOutlined
        className="text-lg mt-4 absolute bottom-12 left-1/2 -translate-x-2/4"
        onClick={() => props.setisshowNav(false)}
      />
      <Dropdown
        menu={{ items: settingItems }}
        placement="topRight"
        trigger={["click"]}
      >
        <SettingOutlined
          className="text-lg mt-4 absolute bottom-2 left-1/2 -translate-x-2/4 cursor-pointer"
        />
      </Dropdown>

      <Modal
        title="退出登录"
        open={isModalOpen}
        onOk={confirmLogout}
        onCancel={() => setIsModalOpen(false)}
        okText="确定"
        cancelText="取消"
      >
        <p>确定要退出登录吗？</p>
      </Modal>
    </>
  );
};

export default memo(LeftNav);
